﻿namespace Common.Unit
{
    public static class StringReplace
    {
        /// <summary>
        ///     替换字符串中的特殊符号赋值为空
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string ReplaceSymbol(this string str)
        {
            str = str.Replace("'", "");
            str = str.Replace(";", "");
            str = str.Replace(":", "");
            str = str.Replace("/", "");
            str = str.Replace("?", "");
            str = str.Replace("<", "");
            str = str.Replace(">", "");
            str = str.Replace(".", "");
            str = str.Replace("#", "");
            str = str.Replace("%", "");
            str = str.Replace("^", "");
            str = str.Replace("//", "");
            str = str.Replace("@", "");
            str = str.Replace("(", "");
            str = str.Replace(")", "");
            str = str.Replace("*", "");
            str = str.Replace("~", "");
            str = str.Replace("`", "");
            str = str.Replace("$", "");

            return str;
        }

        /// <summary>
        ///     替换SqlServer注入关键字
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string ReplaceMsSqlInject(this string str)
        {
            if (string.IsNullOrEmpty(str)) return str;

            str = str.ToLower();
            const string words = "exec|execute|insert|select|delete|update|chr|mid|master|truncate|char|declare" +
                        "|and|or|1=1|drop|create|begin|commit|rollback|tran|waitfor" +
                        "|--|/*|*/|*|'|;|user|using" +
                        "|avg|sum|count|max|min|stdev|group|by|having";

            var wordsArray = words.Split('|');
            foreach (var wordItem in wordsArray)
                str = str.Replace(wordItem, "");
            return str;
        }

        /// <summary>
        ///     替换SqlServer转义字符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string RelaceMsSqlEscape(this string str)
        {
            if (string.IsNullOrEmpty(str)) return str;
            str = str.Trim(' ');
            str = str.Replace("[", "[[]"); //左中括号在Like中默认为空的问题,右中括号没有这个问题
            str = str.Replace("_", "[_]"); //一个下划线匹配任意字符的问题
            str = str.Replace("%", "[%]"); //模糊查询的问题
            return str;
        }
    }
}